document.addEventListener("DOMContentLoaded", function() {
    // 从 URL 查询参数中获取 message，并显示到页面和弹窗
    const params = new URLSearchParams(window.location.search);
    const message = params.get('message');
    if (message) {
      alert(message);
      const messageElem = document.getElementById("message");
      if (messageElem) {
        messageElem.textContent = message;
      }
    }

    // 处理表单提交
    const form = document.querySelector("form");
    form.addEventListener("submit", function(event) {
      event.preventDefault();
      const formData = new FormData(form);
      
      // 获取用户名的值
      const username = formData.get('username');

      fetch("/login", {
        method: "POST",
        headers: {
          "X-Requested-With": "XMLHttpRequest"
        },
        body: formData
      })
      .then(response => {
        if (!response.ok) {
          return response.json().then(errorData => {
            throw errorData;
          });
        }
        return response.json();
      })
      .then(data => {
        // 使用从表单中获取的 username 值
        localStorage.setItem('currentUser', username);
        // 若后端返回了重定向地址，则跳转
        if (data.redirect) {
          window.location.href = data.redirect;
        }
      })
      .catch(error => {
        // 如果返回了错误信息，显示在页面
        const messageElem = document.getElementById("message");
        if (messageElem) {
          messageElem.textContent = error.error || "登录失败：请检查用户名和密码";
        }
      });
    });
  });